﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Nop.Admin.Models.Customers;
using Nop.Admin.Models.Security;
using Nop.Core;
using Nop.Core.Domain.Catalog;
using Nop.Services.Catalog;
using Nop.Services.Customers;
using Nop.Services.Localization;
using Nop.Services.Logging;
using Nop.Services.Security;

namespace Nop.Admin.Controllers
{
    public class DanielController : BaseAdminController
    {
        #region Fields

        private readonly ILogger _logger;
        private readonly IWorkContext _workContext;
        private readonly ICategoryService _categoryService;
        private readonly ICustomerService _customerService;
        private readonly ILocalizationService _localizationService;

        #endregion


        #region Constructors

        public DanielController(ILogger logger, IWorkContext workContext,
            ICategoryService permissionService,
            ICustomerService customerService, ILocalizationService localizationService)
		{
            this._logger = logger;
            this._workContext = workContext;
            this._categoryService = permissionService;
            this._customerService = customerService;
            this._localizationService = localizationService;
		}

        #endregion


        #region Methods


        public ActionResult Permissions()
        {
            //if (!_permissionService.Authorize(StandardPermissionProvider.ManageAcl))
            //    return AccessDeniedView();

            var model = new PermissionCategoryMappingModel();

            var categoryRecords = _categoryService.GetAllCategories();
            var customerRoles = _customerService.GetAllCustomerRoles(true);
            foreach (var pr in categoryRecords)
            {
                model.AvailableCategories.Add(new Category()
                {
                    //Name = pr.Name,
                    Name = pr.Name,
                    MetaKeywords = pr.MetaKeywords,
                    MetaDescription = pr.MetaDescription
                });
            }
            foreach (var cr in customerRoles)
            {
                model.AvailableCustomerRoles.Add(new CustomerRoleModel()
                {
                    Id = cr.Id,
                    Name = cr.Name
                });
            }
            foreach (var pr in categoryRecords)
                foreach (var cr in customerRoles)
                {
                    bool allowed = pr.CustomerRoles.Count(x => x.Id == cr.Id) > 0;
                    if (!model.Allowed.ContainsKey(pr.Name))
                        model.Allowed[pr.Name] = new Dictionary<int, bool>();
                    model.Allowed[pr.Name][cr.Id] = allowed;
                }

            return View(model);
        }


        [HttpPost, ActionName("Permissions")]
        public ActionResult PermissionsSave(FormCollection form)
        {
            //if (!_permissionService.Authorize(StandardPermissionProvider.ManageAcl))
            //    return AccessDeniedView();

            var categoryRecords = _categoryService.GetAllCategories();
            var customerRoles = _customerService.GetAllCustomerRoles(true);


            foreach (var cr in customerRoles)
            {
                string formKey = "allow_" + cr.Id;
                var permissionRecordSystemNamesToRestrict = form[formKey] != null ? form[formKey].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() : new List<string>();

                foreach (var pr in categoryRecords)
                {

                    bool allow = permissionRecordSystemNamesToRestrict.Contains(pr.Name);
                    if (allow)
                    {
                        if (pr.CustomerRoles.FirstOrDefault(x => x.Id == cr.Id) == null)
                        {
                            pr.CustomerRoles.Add(cr);
                            _categoryService.UpdateCategory(pr);
                        }
                    }
                    else
                    {
                        if (pr.CustomerRoles.FirstOrDefault(x => x.Id == cr.Id) != null)
                        {
                            pr.CustomerRoles.Remove(cr);
                            _categoryService.UpdateCategory(pr);
                        }
                    }
                }
            }

            SuccessNotification(_localizationService.GetResource("Admin.Configuration.ACL.Updated"));
            return RedirectToAction("Permissions");
        }

        public ActionResult Index()
        {
            return View();
        }

        #endregion

    }
}